<template>
    <div>
        <Card>
            <tables 
            ref="tables"{if condition="$buttons['addButtonShow']"}            
            :addButton="{ show: showButtonPermission('{$buttons['addButtonShow']['permission']}'), icon: '{$buttons['addButtonShow']['logo']}', type: '{$buttons['addButtonShow']['type']}', title: '{$buttons['addButtonShow']['title']}', confirm: {if condition="$buttons['addButtonShow']['confirm']"}true{else /}false{/if}  }"
{else /}
            :addButton="{ show: false }"
{/if}
            pageShow
            searchable
            search-place="top"
            :loading="loading"
            v-model="tableData"
            :page="page" 
            :columns="columns" 
            :drawer="drawer"
            :myModal="myModal"
{if condition="$buttons['deleteButtonShow']"}
            @on-delete="handleDelete" 
{/if}
            @page-change="handlePage" 
{if condition="$buttons['addButtonShow']"}
            @table-add-data="addData"
{/if}
{if condition="$buttons['editButtonShow']"}
            @table-edit-data="editData"
{/if}
            @my-modal-close="handleModalClose"
            @on-my-modal-ok="handleMyModalOk"
{volist name="$buttons['rowButtons']" id="br"}
            @my-table-{$br.name}-data="myButtons.handle{:tableNameToModelName($br.name)}"
{/volist}
            >
{notempty name="$buttons['beforeSearchButtons']"}
                <!--表头搜索前置按钮-->
                <template slot="beforeSearch">
{volist name="$buttons['beforeSearchButtons']" id="bb"}
{if condition="$bb.confirm"}
                    <Poptip
                    confirm
                    title="你确定要{$bb.title}吗?"
                    @on-ok="myButtons.handle{:tableNameToModelName($bb.name)}"
                    >
                        <Button type="{$bb.type}" v-show="showButtonPermission('{$bb.permission}')" icon="{$bb.logo}" class="my-before-search-button">{$bb.title}</Button>
                    </Poptip>
{else /}
                    <Button type="{$bb.type}" v-show="showButtonPermission('{$bb.permission}')" @click="myButtons.handle{:tableNameToModelName($bb.name)}" icon="{$bb.logo}" class="my-before-search-button">{$bb.title}</Button>
{/if}
{/volist}
                </template>
{/notempty}
                <!--表头搜索-->
                <template slot="mySearch">
{volist name="search" id="s"}
{if condition="$types[$s][0] == 'input'"}
                    <Input v-model="searchField.{$s}" class="search-input my-search" placeholder="请输入{$alias[$s]}"/>
{elseif  condition="$types[$s][0] == 'select' || $types[$s][0] == 'radio' || $types[$s][0] == 'checkbox'"/}
                    <Select v-model="searchField.{$s}" class="search-col my-search" placeholder="请选择{$alias[$s]}">
                      <Option v-for="item in mySelectData.{$s}" :value="item.{$init_conf[$s]['valueKey']}" :key="`my-search-{$s}-`+item.{$init_conf[$s]['valueKey']}">{{ item.{$init_conf[$s]['nameKey']} }}</Option>
                    </Select>
{elseif condition="$types[$s][0] == 'datepicker'"/}
                    <DatePicker type="{$types[$s][1]}" v-model="searchField.{$s}" placement="bottom-end" placeholder="选择{$alias[$s]}"></DatePicker>
{elseif condition="$types[$s][0] == 'timepicker'"/}
                    <TimePicker type="{$types[$s][1]}" v-model="searchField.{$s}" placement="bottom-end" placeholder="选择{$alias[$s]}"></TimePicker>
{/if}
{/volist}
                    <Button class="search-btn" type="primary" icon="md-search" @click="handleMySearch">搜索</Button>
                </template>
{if condition="$buttons['exportButtonShow'] || !empty($buttons['afterSearchButtons'])"}
                <template slot="afterSearch">
{if condition="$buttons['exportButtonShow']"}
{if condition="$buttons['exportButtonShow']['confirm']"}
                    <!--表头导出-->
                    <Poptip
                    confirm
                    title="你确定要{$buttons['exportButtonShow']['title']}吗?"
                    @on-ok="exportExcel"
                    >
                        <Button class="my-after-search-button" v-show="showButtonPermission('{$buttons['exportButtonShow']['permission']}')" type="{$buttons['exportButtonShow']['type']}" icon="{$buttons['exportButtonShow']['logo']}">{$buttons['exportButtonShow']['title']}</Button>
                    </Poptip>
{else /}
                    <!--表头导出-->
                    <Button class="my-after-search-button" v-show="showButtonPermission('{$buttons['exportButtonShow']['permission']}')" type="{$buttons['exportButtonShow']['type']}" icon="{$buttons['exportButtonShow']['logo']}" @click="exportExcel">导出</Button>
{/if}
{/if}
{volist name="$buttons['afterSearchButtons']" id="ba"}
{if condition="$ba.confirm"}
                    <Poptip
                    confirm
                    title="你确定要{$bb.title}吗?"
                    @on-ok="myButtons.handle{:tableNameToModelName($ba.name)}"
                    >
                    <Button class="my-after-search-button" v-show="showButtonPermission('{$bb.permission}')" type="{$ba.type}" icon="{$ba.logo}">{$ba.title}</Button>
                    </Poptip>
{else /}
                    <Button class="my-after-search-button" v-show="showButtonPermission('{$bb.permission}')" type="{$ba.type}" icon="{$ba.logo}" @click="myButtons.handle{:tableNameToModelName($ba.name)}">{$ba.title}</Button>
{/if}
{/volist}
                </template>
{/if}
                <!--添加编辑表单-->
                <Form ref="sform" :model="formField" slot="drawer" label-position="top">
                    <Row :gutter="32">
{volist name="edit" id="f"}
{if condition="$f != $pk && $types[$f][0] != 'upload' && $types[$f][0] != 'textarea'"}
                        <Col span="12">
{eq name="$types[$f][0]" value="input"}
                            <FormItem label="{$alias[$f]}" prop="{$f}" required>
                                <Input v-model="formField.{$f}" placeholder="请输入{$alias[$f]}"/>
                            </FormItem>
{/eq}
{eq name="$types[$f][0]" value="select"}
                            <FormItem label="{$alias[$f]}" prop="{$f}" required>
                                <Select v-model="formField.{$f}" placeholder="请选择{$alias[$f]}">
                                    <Option v-for="item in mySelectData.{$f}" :value="item.{$init_conf[$f]['valueKey']}" :key="`my-sel-{$f}-`+item.{$init_conf[$f]['valueKey']}">{{ item.{$init_conf[$f]['nameKey']} }}</Option>
                                </Select>
                            </FormItem>
{/eq}
{eq name="$types[$f][0]" value="radio"}
                            <FormItem label="{$alias[$f]}" class="my-form-item" required></FormItem>
                            <FormItem prop="{$f}" required>
                                <RadioGroup v-model="formField.{$f}">
                                    <Radio v-for="item in mySelectData.{$f}" :label="item.{$init_conf[$f]['valueKey']}" :key="`my-radio-{$f}-`+item.{$init_conf[$f]['valueKey']}">
                                        <span>{{ item.{$init_conf[$f]['nameKey']} }}</span>
                                    </Radio>
                                </RadioGroup>
                            </FormItem>
{/eq}
{eq name="$types[$f][0]" value="checkbox"}
                            <FormItem label="{$alias[$f]}" class="my-form-item" required></FormItem>
                            <FormItem prop="{$f}" required>
                                <CheckboxGroup v-model="formField.{$f}">
                                    <Checkbox v-for="item in mySelectData.{$f}" :label="item.{$init_conf[$f]['valueKey']}" :key="`my-checkbox-{$f}-`+item.{$init_conf[$f]['valueKey']}">
                                        <span>{{ item.{$init_conf[$f]['nameKey']} }}</span>
                                    </Checkbox>
                                </CheckboxGroup>
                            </FormItem>
{/eq}
{eq name="$types[$f][0]" value="datepicker"}
                            <FormItem label="{$alias[$f]}" prop="{$f}" required>
                                <DatePicker type="{$types[$f][1]}" placeholder="请选择{$alias[$f]}" v-model="formField.{$f}" style="width:100%;"></DatePicker>
                            </FormItem>
{/eq}
{eq name="$types[$f][0]" value="timepicker"}
                            <FormItem label="{$alias[$f]}" prop="{$f}" required>
                                <TimePicker type="{$types[$f][1]}" placeholder="请选择{$alias[$f]}" v-model="formField.{$f}" style="width:100%;"></TimePicker>
                            </FormItem>
{/eq}
                        </Col>
{/if}
{/volist}
                    </Row>
                    <Row :gutter="32">
{volist name="uploads.single" id="us"}
                        <Col span="12">
                            <SingleUpload title="{$alias[$us]}" field="{$us}" {if condition="$init_conf[$us]['uploadApi']"}action="{$init_conf[$us]['uploadApi']}"{/if} :up="uploadInit.{$us}" :params="uploadParam.{$us}" :format="uploadFormat.{$us}" :maxSize="uploadMaxSize.{$us}" @upload-success="uploadSuccess.{$us}" @on-remove="uploadRemove.{$us}"></SingleUpload>
                        </Col>
{/volist}
                    </Row>
{volist name="uploads.multiple" id="um"}
                    <Row>
                        <Col span="12">
                            <MultipleUpload title="{$alias[$um]}" field="{$um}" {if condition="$init_conf[$um]['uploadApi']"}action="{$init_conf[$um]['uploadApi']}"{/if} :uplist="uploadInit.{$um}" :params="uploadParam.{$um}" :format="uploadFormat.{$um}" :maxSize="uploadMaxSize.{$um}" @upload-success="uploadSuccess.{$um}" @on-remove="uploadRemove.{$um}"></MultipleUpload>
                        </Col>
                    </Row>
{/volist}
                    <Row :gutter="32">
{volist name="textarea.textarea" id="tt"}
                        <Col span="12">
                            <FormItem label="{$alias[$tt]}"  required>
                                <Input v-model="formField.{$tt}" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="请输入{$alias[$tt]}"></Input>
                            </FormItem>
                        </Col>
{/volist}
                    </Row>
{volist name="textarea.editor" id="te"}
                    <Row>
                        <neditor v-model="formField.{$te}" title="{$alias[$te]}" class="my-editor"></neditor>
                    </Row>
{/volist}
                    <Row class="my-form-buttons">
                        <FormItem>
                            <Button type="primary" @click="handleForm()">保存</Button>
                            <Button type="warning" style="marginLeft: 8px" @click="formReset(false)">重置</Button>
                            <Button style="marginLeft: 8px" @click="drawer.show = false">取消</Button>
                        </FormItem>
                    </Row>
                </Form>
            </tables> 
        </Card>
    </div>
</template>

<script>
import Tables from '_c/tables'
{notempty name="$uploads['single']"}
import SingleUpload from '_c/uploads/single-upload.vue'
{/notempty}
{notempty name="$uploads['multiple']"}
import MultipleUpload from '_c/uploads/multiple-upload.vue'
{/notempty}
{notempty name="$textarea['editor']"}
import Neditor from '_c/neditor'{/notempty}

import { {volist name="api" id="a"}{$a}{lt name="$i" value=":count($api)"},{/lt}{/volist}{notempty name="$remote"},{volist name="remote" id="r"}{$r.name}{lt name="$i" value=":count($remote)"},{/lt}{/volist}{/notempty} } from '@/api/{$apiDoc}'
import { hasButtonPermission } from '@/libs/util'

export default {
  name: '{$component}',
  components: {
    Tables{notempty name="$uploads['single']"},
    SingleUpload{/notempty}{notempty name="$uploads['multiple']"},
    MultipleUpload
    {/notempty}{notempty name="$textarea['editor']"},
    Neditor
    {/notempty}
  },
  data () {
    return {
      loading: true,
      //分页配置
      page: {
        page: 1,
        total: 0,
        pageSize: 10
      },
      searchField: {
{volist name="search" id="s"}
        {$s}: ''{lt name="$i" value=":count($search)"},
{/lt}
{/volist}

      },
      columns: [
{volist name="list" id="l"}
        { title: '{$alias[$l]}', key: '{$l}' },
{/volist}
        {
          title: '操作',
          key: 'handle',
          button: [
{if condition="$buttons['editButtonShow']"}
            (h, params, vm) => {
              if(!this.showButtonPermission('{$buttons["editButtonShow"]["permission"]}')) return h('')
              return h('Button', {
                props: {
                  type: '{$buttons["editButtonShow"]["type"]}',
                  size: 'small',
                  icon: '{$buttons["editButtonShow"]["logo"]}'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  'click' : () => {
                    vm.$emit('table-edit-data', params.row, vm)
                  }
                }
              },'{$buttons["editButtonShow"]["title"]}')
            },{/if}
{if condition="$buttons['deleteButtonShow']"}

            (h, params, vm) => {
              if(!this.showButtonPermission('{$buttons["deleteButtonShow"]["permission"]}')) return h('')
              return h('Poptip', {
                  props: {
                    confirm: true,
                    title: '你确定要{$buttons["deleteButtonShow"]["title"]}吗?'
                  },
                  on: {
                    'on-ok': () => {
                      vm.$emit('on-delete', params, vm)
                    }
                  }
                }, 
                [
                  h('Button', {
                    props: {
                      type: '{$buttons["deleteButtonShow"]["type"]}',
                      size: 'small',
                      icon: '{$buttons["deleteButtonShow"]["logo"]}'
                    },
                    style: {
                      marginRight: '5px'
                    }
                  },'{$buttons["deleteButtonShow"]["title"]}')
                ]
              )
            }{/if}{volist name="$buttons['rowButtons']" id="br"},
            (h, params, vm) => {
              if(!this.showButtonPermission('{$br.permission}')) return h('')
{if condition="$br.confirm"}
              return h('Poptip', {
                  props: {
                    confirm: true,
                    title: '你确定要{$br.title}吗?'
                  },
                  on: {
                    'on-ok': () => {
                      vm.$emit('my-table-{$br.name}-data', params.row)
                    }
                  }
                }, 
                [
                  h('Button', {
                    props: {
                      type: '{$br.type}',
                      size: 'small',
                      icon: '{$br.logo}'
                    },
                    style: {
                      marginRight: '5px'
                    }
                  },'{$br.title}')
                ]
              )
{else /}
              return h('Button', {
                props: {
                  type: '{$br.type}',
                  size: 'small',
                  icon: '{$br.logo}'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  'click' : () => {
                    vm.$emit('my-table-{$br.name}-data', params.row)
                  }
                }
              },'{$br.title}')
{/if}
            }
{/volist}
          ]
        }
      ],
      tableData: [],
      drawer: {
        title: '',
        show: false
      },
      myModal: {
        title: '',
        show: false,
        width: '800px'
      },
      formField: {
{volist name="edit" id="e"}
        {$e}: {if condition="$types[$e][0] == 'checkbox' || ($types[$e][0] == 'upload' && $types[$e][1] == 'multiple')"}[]{else/}''{/if}{lt name="$i" value=":count($edit)"},
{/lt}
{/volist}

      },
      mySelectData: {
{volist name="conf" id="c"}
        {$c.field}: [
{volist name="c.selfDef" id="cs" key="k"}
          {
            {$c.valueKey}: {$cs.id},
            {$c.nameKey}: '{$cs.title}'
          }{lt name="$k" value=":count($c['selfDef'])"},
{/lt}
{/volist}
        
        ]{lt name="$i" value=":count($conf)"},
{/lt}

{/volist}

      }{notempty name="$uploads"},
      uploadInit: {
{volist name="uploads.single" id="us"}
        {$us}: {}{lt name="$i" value=":count($uploads.single)"},
{/lt}
{/volist}{notempty name="uploads.single"},{/notempty}{volist name="uploads.multiple" id="um"}
        {$um}: []{lt name="$i" value=":count($uploads.multiple)"},
{/lt}
{/volist}

      },
      uploadParam: {
{volist name="uploads.single" id="us"}
        {$us}: {
          path: '{$init_conf[$us]["uploadPath"]}'
        }{lt name="$i" value=":count($uploads.single)"},
{/lt}
{/volist}{notempty name="uploads.single"},{/notempty}{volist name="uploads.multiple" id="um"}
        {$um}: {
          path: '{$init_conf[$um]["uploadPath"]}'
        }{lt name="$i" value=":count($uploads.multiple)"},
{/lt}
{/volist}        
      },
      uploadFormat: {
{volist name="uploads.single" id="us"}
        {$us}: [{volist name="init_conf[$us]['uploadFormat']" id="iu" key="k"}'{$iu}'{lt name="$k" value=":count($init_conf[$us]['uploadFormat'])"},{/lt}{/volist}]{lt name="$i" value=":count($uploads.single)"},
{/lt}
{/volist}{notempty name="uploads.single"},{/notempty}{volist name="uploads.multiple" id="um"}
        {$um}: [{volist name="init_conf[$um]['uploadFormat']" id="iu" key="k"}'{$iu}'{lt name="$k" value=":count($init_conf[$um]['uploadFormat'])"},{/lt}{/volist}]{lt name="$i" value=":count($uploads.multiple)"},
{/lt}
{/volist}        
      },
      uploadMaxSize: {
{volist name="uploads.single" id="us"}
        {$us}: 2048{lt name="$i" value=":count($uploads.single)"},
{/lt}
{/volist}{notempty name="uploads.single"},{/notempty}{volist name="uploads.multiple" id="um"}
        {$um}: 2048{lt name="$i" value=":count($uploads.multiple)"},
{/lt}
{/volist}        
      },
      uploadRemove: {
{volist name="uploads.single" id="us"}
        {$us}: (field) => {
          this.formField[field] = ''
        }{lt name="$i" value=":count($uploads.single)"},
{/lt}
{/volist}{notempty name="uploads.single"},{/notempty}{volist name="uploads.multiple" id="um"}
        {$um}: (file, field) => {
          this.formField[field] = this.formField[field].filter((item, index) => item != file.name)
        }{lt name="$i" value=":count($uploads.multiple)"},
{/lt}
{/volist}        
      },
      uploadSuccess: {
{volist name="uploads.single" id="us"}
        {$us}: (name) => {
          this.formField.{$us} = name
          console.log(name)
        }{lt name="$i" value=":count($uploads.single)"},
{/lt}
{/volist}{notempty name="uploads.single"},{/notempty}{volist name="uploads.multiple" id="um"}
        {$um}: (name) => {
          this.formField.{$um}.push(name)
          console.log(name)
        }{lt name="$i" value=":count($uploads.multiple)"},
{/lt}
{/volist}        
      }{/notempty}{if condition="$buttons['hasSelfdefButton']"},
      //自定义按钮事件
      myButtons: {
{volist name="$buttons['beforeSearchButtons']" id="bb"}
        handle{:tableNameToModelName($bb.name)}: () => {
          console.log('{$bb.title}按钮的方法在这儿写')
        },  
{/volist}
{volist name="$buttons['afterSearchButtons']" id="ba"}
        handle{:tableNameToModelName($ba.name)}: () => {
          console.log('{$ba.title}按钮的方法在这儿写')
        },  
{/volist}
{volist name="$buttons['rowButtons']" id="br"}
        handle{:tableNameToModelName($br.name)}: (params) => {
          console.log(params)
          console.log('{$br.title}按钮的方法在这儿写')
        },  
{/volist}

      }
{/if}

    }
  },
  methods: {
    //监听分页
    handlePage (page, size) {
      console.log('分页的方法在这里写')
      this.loading = true
      {$api['listApi']}({ page, pageSize: size }).then(res => {
        this.page.total = res.data.count
        this.tableData = res.data.data
        this.loading = false
      })  
    },
    //查询方法
    handleMySearch () {
      console.log('查询的方法在这里写')
      let field = this.searchField
      {$api['listApi']}(field).then(res => {
        console.log(res)
        this.tableData = res.data.data
        this.page.page  = 1
        this.page.total = res.data.count
      })
    },
    //监听添加
    addData () {
      this.opentype = 'drawer'
      console.log('新增的方法在这里写')
      this.drawer.title = '添加'
      this.drawer.show = true
      this.formReset()
      this.formField.save_type = 1
    },
    //监听编辑
    editData (oldData, vm) {
      this.opentype = 'drawer'
      this.drawer.title = '编辑'
      for (let key in this.formField){
        this.formField[key] = oldData[key]
      }
      this.formField.id = oldData.{$pk}

      this.formField.save_type = 2
      this.drawer.show = true
      console.log('编辑的方法在这里写')
    },
    //处理表单提交
    handleForm () {
      if(this.formField.save_type == 1){
        {$api['createApi']}(this.formField).then(res => {
          if(res.data.code == 200){
            this.drawer.show = false
            this.$Message.success(res.data.msg);
            this.page.total++
            let lastP = Math.ceil(this.page.total / this.page.pageSize)
            this.reloadTable(lastP)
          }else{
            this.$Message.error(res.data.msg);
          }
        })
      }else if(this.formField.save_type == 2){
        {$api['editApi']}(this.formField).then(res => {
          if(res.data.code == 200){
            this.drawer.show = false
            this.$Message.success(res.data.msg);
            this.reloadTable()
          }else{
            this.$Message.error(res.data.msg);
          }
        })
      }
    },
    //监听删除事件
    handleDelete (params, vm) {
      let id = params.row.{$pk}
      
      {$api['deleteApi']}(id).then(res => {
        if(res.data.code == 200){
          this.$Message.success(res.data.msg);
          this.page.total--
          vm.$emit('input', params.tableData.filter((item, index) => index !== params.row.initRowIndex))
          if((this.page.total % this.page.pageSize) == 0){
            this.reloadTable(this.page.page - 1);
          } 
        }else{
          this.$Message.error(res.data.msg);
        }
      })
    },
    //监听弹出框关闭
    handleModalClose() {

    },
    //监听弹出框确认按钮
    handleMyModalOk() {

    },
    //表单重置
    formReset (all = true) {
      this.$refs.sform.resetFields();
      if(all){
        this.formField.{$pk} = ''
      }
    },
    //导出
    exportExcel () {
      this.$refs.tables.exportCsv({
        filename: `table-${(new Date()).valueOf()}.csv`
      })
    },
    //表格重载
    reloadTable (page) {
      let curr = page ? page : this.page.page
      this.loading = true
      {$api['listApi']}({ page: curr, pageSize: this.page.pageSize }).then(res => {
        this.page.total = res.data.count
        this.tableData = res.data.data
        this.page.page = curr
        this.loading = false
      })
    }{notempty name="$remote"},
    initSelectData () {
{volist name="remote" id="r"}
      {$r.name}().then(res => {
        this.mySelectData.{$r.field} = res.data.data
      })

{/volist}
    }
    {/notempty}{if condition="$buttons['hasButton']"},
    showButtonPermission (permission) {
      return hasButtonPermission(permission, this.$store.state.user.buttonAccess, this.$store.state.user.access)      
    }
{/if}
  
  },
  //挂载后方法
  mounted () {
    let {
      page,
      pageSize
    } = this.page
    {$api['listApi']}({ page, pageSize }).then(res => {
      this.page.total = res.data.count
      this.tableData = res.data.data
      this.loading = false
    })
{notempty name="$remote"}
    this.initSelectData()
{/notempty}
  }
}
</script>
<style scoped>
.my-form-buttons{
  margin-top: 20px;
}
.my-form-item{
  margin-bottom: 0;
}
.my-search{
  margin-right: 2px;
}
.my-before-search-button{
  margin-right: 2px;
}
.my-after-search-button{
  margin-left: 2px;
}
.ivu-select-dropdown{
  z-index: 1100;
}
</style>